package smartutils;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * the description for class ReentrantLockExample
 *
 * @author xiyuan-lgz 2023-11-26 @version v1.0.0 新建与整理
 */
public class ReentrantLockExample {
    private static final ReentrantLock lock = new ReentrantLock();
    
    public static void main(String[] args) {
        // 创建多个线程，模拟并发访问
        Thread thread1 = new Thread(() -> performTask("Thread 1"));
        Thread thread2 = new Thread(() -> performTask("Thread 2"));
        Thread thread3 = new Thread(() -> performTask("Thread 3"));
        
        // 启动线程
        thread1.start();
        thread2.start();
        thread3.start();
    }
    
    private static void performTask(String threadName) {
        System.out.println(threadName + " is trying to acquire the lock.");
        try {
            // 尝试获取锁
            if (lock.tryLock(5, TimeUnit.SECONDS)) {
                try {
                    // 成功获取锁后的操作
                    System.out.println(threadName + " acquired the lock and is performing the task.");
                    // 模拟执行任务
                    Thread.sleep(10000);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
                finally {
                    // 释放锁
                    lock.unlock();
                    System.out.println(threadName + " released the lock.");
                }
            }
            else {
                System.out.println(threadName + " Time out.");
            }
        }catch (InterruptedException e) {
            e.getMessage();
        }
        
    }
}
